package com.hjk.waibao.mj.util;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jfinal.kit.PropKit;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author hjk
 * @Date 2020/4/22
 **/
public class AliSendMsg {
    public static final String ACCESS_KEY_ID = PropKit.get("aliyun.accessKeyId");
    public static final String ACCESS_SECRET = PropKit.get("aliyun.accessSecret");
    public static final Map<String, Sms> SMS_MAP = new HashMap<>();

    /**
     * @param phone 接收手机号
     * @return 错误的话返回错误信息，返回null为正确
     */
    public static String sendSms(String phone) {
        if (SMS_MAP.get(phone) != null) {
            if (System.currentTimeMillis() - SMS_MAP.get(phone).getTimestamp() < 60000) {
                return "发送频率过快，请稍后再试";
            }
        }
        int code = RandomUtil.randomInt(100000, 999999);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "评论助手");
        request.putQueryParameter("TemplateCode", "SMS_188640706");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            if ("OK".equalsIgnoreCase(jsonObject.getString("Code"))) {
                SMS_MAP.put(phone, new Sms(phone, code + "", System.currentTimeMillis()));
                return null;
            } else {
                return "与验证码服务器交流失败：" + jsonObject.getString("Message");
            }
        } catch (Exception e) {
            return "与验证码服务器交流失败";
        }
    }

    public static boolean validate(String phone, String code) {
        if (SMS_MAP.get(phone) == null || !SMS_MAP.get(phone).getCode().equals(code) || System.currentTimeMillis() - SMS_MAP.get(phone).getTimestamp() > 1000 * 60 * 10) {
            return false;
        } else {
            SMS_MAP.get(phone).setTimestamp(0L);
            return true;
        }
    }

    @Data
    @AllArgsConstructor
    private static class Sms {
        String phone;
        String code;
        Long timestamp;
    }
}